package blog.controller;

import blog.common.Result;
import blog.entity.Login;
import blog.entity.User;
import blog.service.LoginService;
import blog.service.UserActionService;
import blog.service.UserService;
import blog.utils.EmailUtil;
import blog.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserActionService userActionService;
    /**
     * 后台登录
     */
    @PostMapping("/adminLogin")
    public Result adminLogin(@RequestBody User user){
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())){
            return Result.error("用户名或密码不能为空");
        }
        //判断账号密码是否都为root
        if (user.getUsername().equals("root") && user.getPassword().equals("root")){
            //返回jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", JwtUtil.getToken(Long.valueOf("1627039473")));
            map.put("user", "root");

            return Result.success(map, "登录成功");
        }else {
            return Result.error("账号或密码错误，请联系作者索要账号密码");
        }

    }


    /**
     * 用户登录
     * @param map
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map map, HttpServletRequest request){
        log.info(map.toString());
        //获取IP地址
        String ip = request.getRemoteAddr();
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        return userService.login(username,password,ip);
    }
    /**
     * 查询用户访问数
     *
     * @return
     */
    @GetMapping ("/findUserVisitCount")
    public Result findUserVisitCount() {
        return userService.findUserVisitCount();
    }
    /**
     * 查询最近访问的用户
     *
     * @return
     */
    @GetMapping("/findUserVisitList")
    public Result findUserVisitList() {
        return userService.findUserVisitList();
    }

    /**
     * 查询用户在文章的行为
     *
     */
    @GetMapping("/findUserArticleAction")
    public Result findUserArticleAction(@RequestParam("aid") int aid, @RequestParam("uid") int uid) {
        return userActionService.findUserArticleAction(aid,uid);
    }
    /**
     * 修改用户信息
     */
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        return userService.updateUser(user);
    }
    /**
     * 发送邮箱给我
     */
    @Autowired
    EmailUtil emailUtil;
    @PostMapping("/sendEmail")
    public Result sendEmail(@RequestBody Map map){
        String content = map.get("content").toString();
        return emailUtil.sendToMe(content);
    }
    /**
     * 添加或修改用户评分
     */
    @PostMapping("/addUserScore")
    public Result addUserScore(@RequestBody Map map){
        int uid = Integer.parseInt(map.get("uid").toString());
        int aid = Integer.parseInt(map.get("aid").toString());
        int score = Integer.parseInt(map.get("score").toString());
        return userActionService.addUserScore(uid,aid,score);
    }
    /**
     * 查看用户评分
     */
    @GetMapping("/findUserScore")
    public Result findUserScore(@RequestParam("uid") int uid,@RequestParam("aid") int aid){
        return userActionService.findUserScore(uid,aid);
    }

    @Autowired
    private LoginService loginService;
    /**
     * 根据ip查询用户地址
     *
     */
    @GetMapping("/findUserAddress")

    public Result findUserAddress(@RequestParam("ip") String ip){
        return loginService.findUserAddress(ip);
    }
    /**
     * 查询用户列表
     */
    //分页查询

    @GetMapping("/page")
    public Result selectByPage(Integer page, Integer pageSize, String name) {
        Page<User> userPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            wrapper.like(User::getUsername, name);
        }
        Page<User> userPage1 = userService.page(userPage, wrapper);
        return Result.success(userPage1);
    }
    /**
     * 根据id查询用户信息
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable String id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable String id) {
        userService.removeById(id);
        return Result.success();
    }


    /**
     * 分页查询登陆日志
     */
    @GetMapping("/loginLog")
    public Result selectLoginLogByPage(Integer page, Integer pageSize, String name) {
        Page<Login> loginLogPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Login> wrapper = new LambdaQueryWrapper<>();
        //按照时间倒序
        wrapper.orderByDesc(Login::getCreateTime);
        if (StringUtils.isNotBlank(name)) {
            wrapper.like(Login::getUname, name);
        }
        Page<Login> loginLogPage1 = loginService.page(loginLogPage, wrapper);
        return Result.success(loginLogPage1);
    }



}